//
//  EditSystemDetailView.swift
//  GreenDeal
//
//  Created by Moennig Q on 2023/3/3.
//

import UIKit
import RxSwift
import RxCocoa

class EditSystemInfoView: GreenNaviBarView {
    lazy var disposeBag = DisposeBag()
    let scrollView = DIYScrollView()
    //panel inverter battery合并在一起的View
    let combineView = SystemInfoCombineView()
    let saveBtn = OperationButton(R.string.localizable.save(),enabled: true)
    override func setUpView() {
        //save btn
        self.addSubview(saveBtn)
        saveBtn.snp.makeConstraints { make in
            make.bottom.equalTo(OperationButton.bottomMargin)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.equalTo(OperationButton.height)
        }
        
        scrollView.drawCorner(byRoundingCorners: [.topLeft,.topRight])
        scrollView.backgroundColor = .white
        self.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.top.equalTo(self.topBackView.snp.bottom).offset(-20)
            make.left.right.equalTo(self)
            make.bottom.equalTo(saveBtn.snp.top)
        }
        let contentView = UIView()
        contentView.backgroundColor = .white
        scrollView.addSubview(contentView)
        
        contentView.snp.makeConstraints { (make) in
            make.top.bottom.equalTo(scrollView)
            make.left.right.equalTo(self)
            make.height.greaterThanOrEqualTo(0)
        }
        contentView.addSubview(combineView)
        combineView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        //
        self.combineView.scrollToViewClosure = { [weak self] type in
            guard let strongSelf = self else {return}
            strongSelf.layoutIfNeeded()
            //跳转到scan部分
            if type == .Panel{
                let recOnTableView = strongSelf.combineView.panelTableView.rectForRow(at: IndexPath(row: strongSelf.combineView.panelTableView.list.count - 1, section: 0))
                let pointOnScrollView = strongSelf.combineView.panelTableView.convert(recOnTableView.origin, to: strongSelf.scrollView)
                strongSelf.scrollView.scrollToView(point: pointOnScrollView, animated: true)
            }else if type == .Inverter{
                let recOnTableView = strongSelf.combineView.inverterTableView.rectForRow(at: IndexPath(row: strongSelf.combineView.inverterTableView.list.count - 1, section: 0))
                let pointOnScrollView = strongSelf.combineView.inverterTableView.convert(recOnTableView.origin, to: strongSelf.scrollView)
                strongSelf.scrollView.scrollToView(point: pointOnScrollView, animated: true)
            }else if type == .Battery{
                let recOnTableView = strongSelf.combineView.batteryCommonView.tableView.rectForRow(at: IndexPath(row: strongSelf.combineView.batteryCommonView.list.count - 1, section: 0))
                let pointOnScrollView = strongSelf.combineView.batteryCommonView.tableView.convert(recOnTableView.origin, to: strongSelf.scrollView)
                strongSelf.scrollView.scrollToView(point: pointOnScrollView, animated: true)
            }
            
        }
    }
    func setData(isBattery: Bool, panels: [InstallationDetailSystemDetailForPanelModel],inverters: [InstallationDetailSystemDetailForInverterModel],batteries: [InstallationDetailSystemDetailForBatteryModel]){
        self.combineView.loadData(isBattery: isBattery, panels: panels, inverters: inverters, batteries: batteries)
        self.checkEverythingValid()
    }
    //MARK: - 必填项数据绑定控制continue btn是否可用
    private func checkEverythingValid(){
        //1.panels
        let panelsValid = self.combineView.panelTableView.rx.observe(Array<InstallationDetailSystemDetailForPanelModel>.self, "list").map({ list in
            var validFlag: Bool = true
            if let list = list {
                list.forEach { panelModel in
                    if panelModel.model == "" || panelModel.watts_per_panel == 0 || panelModel.number_panels == 0{
                        validFlag = false
                    }
                }
            }
            return validFlag
        }).share(replay: 1)
        //2.inverter
        let inverersValid = self.combineView.inverterTableView.rx.observe(Array<InstallationDetailSystemDetailForInverterModel>.self, "list").map({ list in
            var validFlag: Bool = true
            if let list = list {
                list.forEach { inverterModel in
                    if inverterModel.inverter_model == "" || inverterModel.number_inverters == 0{
                        validFlag = false
                    }
                }
            }
            return validFlag
        }).share(replay: 1)
        
        //3.battery
        let isBatteryValid = self.combineView.batteryCommonView.isBattery.map({$0}).share(replay: 1)
        let batteriesValid = self.combineView.batteryCommonView.rx.observe(Array<InstallationDetailSystemDetailForBatteryModel>.self, "list").map({ list in
            var validFlag: Bool = true
            if let list = list {
                list.forEach { batteryModel in
                    if batteryModel.battery_model == "" || batteryModel.number_batteries == 0{
                        validFlag = false
                    }
                }
            }
            return validFlag
        }).share(replay: 1)
        //整个battery 信息是否有效
        let batteryInfoValid = Observable.combineLatest(
            isBatteryValid,
            batteriesValid
          ) { !$0 || ($0 && $1)}
          .share(replay: 1)
        //6.合并
        let everythingValid = Observable.combineLatest(
            panelsValid,
            inverersValid,
            batteryInfoValid
          ) {
              if $0 && $1 && $2 {
                  return true
              }
              return false
          }
          .share(replay: 1)
        //
        everythingValid.subscribe { [weak self] (valid) in
            guard let strongSelf = self else {return}
            if valid {
                strongSelf.saveBtn.enableBtn()
            }else{
                strongSelf.saveBtn.disableBtn()
            }
        }.disposed(by: self.disposeBag)
    }
    //MARK: - 滚动到无效的行
    fileprivate func scrollToInvalidRow(panelRow: Int? = nil , inverterRow: Int? = nil, batteryRow: Int? = nil){
        if let row = panelRow {//panel 没有检验通过的第一行
            let cellFame = self.combineView.panelTableView.rectForRow(at: IndexPath(row: row, section: 0))
            let offsetY = self.scrollView.convert(cellFame, from: self.combineView.panelTableView).origin.y
            self.scrollView.setContentOffset(CGPoint(x: 0, y: offsetY), animated: true)
        }else if let row = inverterRow  {//inverter 没有检验通过的第一行
            let cellFame = self.combineView.inverterTableView.rectForRow(at: IndexPath(row: row, section: 0))
            let offsetY = self.scrollView.convert(cellFame, from: self.combineView.inverterTableView).origin.y
            self.scrollView.setContentOffset(CGPoint(x: 0, y: offsetY), animated: true)
        }else if let row = batteryRow  {//battery 没有检验通过的第一行
            //cell在tableview上的frame
            let cellFame = self.combineView.batteryCommonView.tableView.rectForRow(at: IndexPath(row: row, section: 0))
            //cell转换在batteryCommonView的frame
            let cellOnCommonViewFrame = self.combineView.batteryCommonView.convert(cellFame, from: self.combineView.batteryCommonView.tableView)
            //cell转换在scrollView的frame
            let offsetY = self.scrollView.convert(cellOnCommonViewFrame, from: self.combineView.batteryCommonView).origin.y
            self.scrollView.setContentOffset(CGPoint(x: 0, y: offsetY), animated: true)
        }
    }
}
